package com.tange.ai.core.demo.setting;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.tange.ai.core.demo.Utils;
import com.tange.ai.core.demo.databinding.ActivitySettingBinding;
import com.tange.core.data.structure.Device;
import com.tange.module.camera.hub.CameraInteraction;
import com.tange.module.camera.reconnection.LimitTimeReconnectionStrategy;
import com.tange.module.camera.reconnection.ReconnectionStrategy;
import com.tg.app.camera.Camera;
import com.tg.data.media.OnICameraListener;

import java.io.UnsupportedEncodingException;

public class SettingActivity extends AppCompatActivity {

    /***************** 查询设备硬件能力 **************/
    public static final int IOTYPE_USEREX_IPCAM_GET_FEATURE_REQ = 0x8024;
    public static final int IOTYPE_USEREX_IPCAM_GET_FEATURE_RESP = 0x8025;

    private static final String PARAM_DEVICE_ITEM = "PARAM_DEVICE_ITEM";

    private ActivitySettingBinding binding;

    private Device device;

    private CameraInteraction cameraInteraction;

    public static void launch(Context context, Device device) {
        Intent intent = new Intent(context, SettingActivity.class);
        intent.putExtra(PARAM_DEVICE_ITEM, device);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivitySettingBinding.inflate(getLayoutInflater());
        binding.statusTv.setMovementMethod(ScrollingMovementMethod.getInstance());
        setContentView(binding.getRoot());
        getSupportActionBar().hide();
        Utils.setStatusBar(this, Color.TRANSPARENT);


        device = (Device) getIntent().getSerializableExtra(PARAM_DEVICE_ITEM);

        if (device == null) {
            Toast.makeText(this, "设备信息为空", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        updateStatus("设备名称：" + device.getName());
        updateStatus("设备类型：" + device.getProductType());
        updateStatus("UUID：" + device.getUuid());
        updateStatus("在线情况：" + (device.online() ? "在线" : "离线"));
        updateStatus("【请点击\"连接设备\"开始连接】");

        // 创建摄像头交互模块
        createCameraInteraction();

        binding.connectDevice.setOnClickListener(v -> {
            updateStatus("尝试连接...");
            cameraInteraction.connect();
            cameraInteraction.setAutoConnect(true); // 后续启用自动重连模式
        });

        binding.requestDeviceInfo.setOnClickListener(v -> {

            // 设备连接成功后，可发送命令，与设备交互
            if (cameraInteraction.camera().isConnected()) {
                // 命令 与 参数，遵循 设备侧文档 来传输
                cameraInteraction.sendCommand(IOTYPE_USEREX_IPCAM_GET_FEATURE_REQ, new byte[] {});
                updateStatus(String.format("已向设备发送命令字 cmd = %x, 请稍侯...", IOTYPE_USEREX_IPCAM_GET_FEATURE_REQ));
            } else {
                Toast.makeText(SettingActivity.this, "未连接成功！", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void updateStatus(String text) {
        binding.statusTv.post(() -> {
            binding.statusTv.setText(binding.statusTv.getText() + text + "\n");
            binding.statusTv.post(() -> {
                int offset = binding.statusTv.getMeasuredHeight() - binding.scrollView.getMeasuredHeight() + binding.statusTv.getLineHeight();
                if (offset < 0) offset = 0;
                binding.scrollView.scrollTo(0, offset);
            });

        });
    }

    private void createCameraInteraction() {
        cameraInteraction = new CameraInteraction(device);
        // 关闭自动连接模式
        cameraInteraction.setAutoConnect(false);
        // 标识不传输音视频，因为当前 为设置场景
        cameraInteraction.setTransportMedia(false);
        // 连接超时最多等待10s
        int maxRetryTime = 10 * 1000;
        cameraInteraction.setReconnectionStrategy(new LimitTimeReconnectionStrategy(maxRetryTime));
        // 监听重试情况
        cameraInteraction.reconnectionStrategy().setCallback(new ReconnectionStrategy.Callback() {
            @Override
            public void onRetry() {
                updateStatus("自动重试中...");
            }

            @Override
            public void onNoMoreRetry() {
                updateStatus("重试超过设置的时长（" + maxRetryTime/1000 + "s），不再重试！");
            }
        });
        cameraInteraction.addOnICameraListeners(new OnICameraListener() {

            // 监听 设备的 连接状态
            @Override
            public void receiveUpdateConnectStates(int state) {
                onReceiveUpdateConnectStates(state);
            }

            // 监听 设备回调的 命令
            @Override
            public void receiveIOCtrlData(int cmd, byte[] data) {
                onReceiveIOCtrlData(cmd, data);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        cameraInteraction.resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        cameraInteraction.pause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cameraInteraction.destroy();
    }

    private void onReceiveUpdateConnectStates(int state) {
        if (state == Camera.CONNECTION_STATE_CONNECTED) {
            binding.statusTv.post(() -> updateStatus("连接成功（可断网演示自动重连）"));
        } else if (state == Camera.CONNECTION_STATE_CONNECTING) {
            binding.statusTv.post(() -> updateStatus("连接中..."));
        } else {
            binding.statusTv.post(() -> updateStatus("连接异常"));
        }
    }

    private void onReceiveIOCtrlData(int cmd, byte[] data) {

        updateStatus(String.format("收到设备回传的命令字 cmd = %x", cmd));


        if (cmd == IOTYPE_USEREX_IPCAM_GET_FEATURE_RESP) {
            try {
                String resp = new String(data, "UTF-8");
                updateStatus("收到的设备信息：\n" + resp);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }
}